/**************************************************************
 *@ProjectName: blweibo
 *@FileName: LRUUtil.java
 *@Date: 2011-5-30
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo.util;

import android.graphics.Bitmap;

/**
 * The Class LRUUtil.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-30
 */
public class LRUUtil {

    /** The arr sm. */
    private SImage[] arrSm;

    /** The max capacity. */
    private final int maxCapacity;

    /** The index. */
    private static int index = 0;

    /**
     * Instantiates a new lRU util.
     * 
     * @param maxCapacity
     *            the max capacity
     */
    public LRUUtil(int maxCapacity) {
        this.maxCapacity = maxCapacity;
        arrSm = new SImage[maxCapacity];
    }

    public void clear() {
        arrSm = new SImage[maxCapacity];
    }

    /**
     * Put.
     * 
     * @param key
     *            the key
     * @param value
     *            the value
     */
    public synchronized void put(String key, Bitmap value) {
        if (index == maxCapacity) {
            arrSm[0].value.recycle();
            for (int i = 0, j = maxCapacity - 1; i < j; i++) {
                arrSm[i] = arrSm[i + 1];
            }
            arrSm[maxCapacity - 1] = new SImage(key, value);
        } else {
            arrSm[index] = new SImage(key, value);
            index++;
        }
    }

    /**
     * Gets the.
     * 
     * @param key
     *            the key
     * @return the bitmap
     */
    public synchronized Bitmap get(String key) {
        for (int i = index - 1; i >= 0; i--) {
            if (arrSm[i].key.equals(key)) {
                SImage temp = arrSm[i];
                for (int j = i; j < index - 1; j++) {
                    arrSm[j] = arrSm[j + 1];
                }
                arrSm[index - 1] = temp;
                return arrSm[i].value;
            }
        }
        return null;
    }

    /**
     * Contains key.
     * 
     * @param key
     *            the key
     * @return true, if successful
     */
    public boolean containsKey(String key) {
        return get(key) != null;
    }

    /**
     * The Class SImage.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-30
     */
    public class SImage {

        /** The key. */
        public String key;

        /** The value. */
        public Bitmap value;

        /**
         * Instantiates a new s image.
         */
        public SImage() {
            key = null;
            value = null;
        }

        /**
         * Instantiates a new s image.
         * 
         * @param s
         *            the s
         * @param b
         *            the b
         */
        public SImage(String s, Bitmap b) {
            key = s;
            value = b;
        }
    }
}
